const utils = require("self-utils");
const db = uniCloud.database();
module.exports = {
	_before:  function () { // 通用预处理器
		
	},
	async add(params){
		if(!this.userInfo.role.includes('manage')){
			return {msg:"没有权限",code:-1}
		}
		if(!this.userInfo.uid){
			return{msg:"没有权限",code:-1};
		} 
		params.price = Number(params.price).toFixed(2)*100
		params.before_price = params.before_price? Number(params.before_price).toFixed(2)*100:null
		return await db.collection("wanshop-mall-goods").add(params);
	},
	async getList(){
		let navData = await db.collection("wanshop-mall-categories").get();
		let goods = await db.collection("wanshop-mall-goods").get();
		navData.data.forEach(item =>{
			let proGroup = goods.data.filter(g =>{
				return g.category_id == item._id
			})
			// 转化价格字段
			proGroup.forEach(g => {
			      g.price = g.price / 100;
			      g.before_price = g.before_price ? g.before_price / 100 : null;
			    })
			
			item.proGroup = proGroup
		})
		
		let newsArr = navData.data.filter(item =>{
			return item.proGroup.length
		})
		
		return newsArr
	},
	async remove(id){
		if(!this.userInfo.role.includes('manage')){
			return {msg:"没有权限",code:-1}
		}
		if(!this.userInfo.uid){
			return{msg:"没有权限",code:-1};
		} 
		let res = await db.collection("wanshop-mall-goods").doc(id).remove();
		return res ;
	},
	async getOne(id){
		let res = await db.collection("wanshop-mall-goods").doc(id).get();
		res.data[0].price = res.data[0].price/100
		res.data[0].before_price = res.data[0].before_price ? res.data[0].before_price/100:null
		return res;
	},
	async update(params){
		if(!this.userInfo.role.includes('manage')){
			return {msg:"没有权限",code:-1}
		}
		if(!this.userInfo.uid){
			return{msg:"没有权限",code:-1};
		} 
		let _params = {...params}
		delete _params._id
		if (_params.price !== undefined) {
		    _params.price = Number(_params.price).toFixed(2) * 100;
		  }
		  if (_params.before_price !== undefined) {
		    _params.before_price = _params.before_price ? Number(_params.before_price).toFixed(2) * 100 : null;
		  }
		await db.collection("wanshop-mall-goods").doc(params._id).update(_params)
	},
	
	// 搜索商品
	async searchGoods(keywords){
			return await db.collection("wanshop-mall-goods").where({
				name:new RegExp(keywords,'gi')
			}).get();
		}
}
